#include "tls_fs.h"

//内核里的base64不支持".",不能用来解码pem证书,这个函数是我修改过的
static const char base64_table[66] =
	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/.";

static int base64_decode(const char *src, int srclen, u8 *dst)
{
	u32 ac = 0;
	int bits = 0;
	int i;
	u8 *bp = dst;

	for (i = 0; i < srclen; i++) {
		const char *p = strchr(base64_table, src[i]);
		if (src[i] == 0xa)
		    continue;

		if (src[i] == '=') {
			ac = (ac << 6);
			bits += 6;
			if (bits >= 8)
				bits -= 8;
			continue;
		}
		if (p == NULL || src[i] == 0){
			return -1;
		}
		ac = (ac << 6) | (p - base64_table);
		bits += 6;
		if (bits >= 8) {
			bits -= 8;
			*bp++ = (u8)(ac >> bits);
		}
	}
	if (ac & ((1 << bits) - 1))
		return -1;
	return bp - dst;
}

int kread_cert(void *data, unsigned char *path) {
    int cert_length = kernel_read_file_from_path(path, 0, &data, INT_MAX, NULL,
                                                 READING_X509_CERTIFICATE);
    if (strncmp((const char *)data, PEM_HEADER, sizeof(PEM_HEADER) - 1) == 0) { //如果是PEM证书, 转成DER格式发送
        cert_length = cert_length - sizeof(PEM_HEADER) - sizeof(PEM_FOOTER);
        cert_length = base64_decode(&((unsigned char *)data)[sizeof(PEM_HEADER)], cert_length, data);

        if (cert_length < 0) {
            printk("base64_decode error!\n");
        }
    }
    return cert_length;
}

int kread_key(void *data, unsigned char *path) {
    int keylen = kernel_read_file_from_path(path, 0, &data, INT_MAX, NULL,
                                                 READING_X509_CERTIFICATE);
    if (strncmp((const char *)data, KEY_HEADER, sizeof(KEY_HEADER) - 1) == 0) { //如果是PEM证书, 转成DER格式发送
        keylen = keylen - sizeof(KEY_HEADER) - sizeof(KEY_FOOTER);
        keylen = base64_decode(&((unsigned char *)data)[sizeof(KEY_HEADER)], keylen, data);

        if (keylen < 0) {
            printk("base64_decode error!\n");
        }
    }
    return keylen;
}
